package com.aloda.ojsandbox.controller;

import cn.hutool.core.bean.BeanUtil;
import com.aloda.ojsandbox.pojo.dto.ExecuteCodeRequest;
import com.aloda.ojsandbox.pojo.dto.ExecuteCodeResponse;
import com.aloda.ojsandbox.pojo.enums.ResponseEnum;
import com.aloda.ojsandbox.properties.CodeSandboxProperties;
import com.aloda.ojsandbox.sandbox.SandboxStrategyExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author aloda
 * @Date 2025/4/30 9:55
 */
@Slf4j
@RestController
@RequestMapping("/sandbox")
public class SandboxController {

    @Resource
    private SandboxStrategyExecutor sandboxStrategyExecutor;

    @Resource
    private CodeSandboxProperties codeSandboxProperties;

    @GetMapping("/health")
    public String health() {
        return "<h1>Hello World. This is OrangeCodeSandbox 0.0.1</h1>";
    }

    /**
     * 执行代码
     *
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/executeCode")
    public ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request
    , HttpServletResponse response) {
        // 基本的认证
        String authHeader = request.getHeader(codeSandboxProperties.getAuthHeader());
        if (!codeSandboxProperties.getAuthHeaderValue().equals(authHeader)) {
            response.setStatus(401);
            return null;
        }
        if (BeanUtil.isEmpty(executeCodeRequest)) {
            return ExecuteCodeResponse.error(ResponseEnum.PARAM_ERROR);
        }
        ExecuteCodeResponse executeCodeResponse = sandboxStrategyExecutor.executeCode(executeCodeRequest);
        return executeCodeResponse;
    }
}
